package com.example.demo.rsa;

import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.AsymmetricAlgorithm;
import cn.hutool.crypto.asymmetric.RSA;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

public class RsaTest {


    /**
     * 数字签名，密钥算法
     */
    private static final String RSA_KEY_ALGORITHM = "RSA";

    static {
        try {
            Security.addProvider(new BouncyCastleProvider());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Test() throws Exception {


        KeyPairGenerator bc = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM, "BC");
        bc.initialize(2014);
        KeyPair keyPair = bc.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();


        //生成公私钥
        StringWriter writer = new StringWriter();

        //公钥
        PemWriter pemWriter = new PemWriter(writer);
        pemWriter.writeObject(new PemObject("PUBLIC KEY", publicKey.getEncoded()));
        pemWriter.flush();
        String publicKeyBase64 = writer.toString();
        System.out.println("生成的公钥：" + publicKeyBase64);

        //私钥
        writer = new StringWriter();
        pemWriter = new PemWriter(writer);
        pemWriter.writeObject(new PemObject("RSA PRIVATE KEY", privateKey.getEncoded()));
        pemWriter.flush();
        String privateKeyBase64 = writer.toString();
        System.out.println("生成的私钥：" + privateKeyBase64);
    }


    public static void main(String[] args) throws Exception {
        Test();
    }
}
